// https://developer.mozilla.org/zh-CN/docs/Mozilla/Add-ons/WebExtensions
const CONFIG_KEY = 'RML_MID_CONFIG';
const IMAGE_KEY = 'RML_MID_IMAGES';
const PAGE_KEY = 'RML_MID_PAGE';

function setStored(keyName, data) {
  return new Promise(resolve => {
    chrome.storage.local.set({ [keyName]: data }, function() {
      resolve();
    });
  });
}

function getStored(keyName) {
  return new Promise(resolve => {
    chrome.storage.local.get(keyName, function(data) {
      resolve(data[keyName]);
    });
  });
}

function removeStored(keyName) {
  return new Promise(resolve => {
    chrome.storage.local.remove(keyName, function(data) {
      resolve();
    });
  });
}

function getStoredConfig() {
  return new Promise(resolve => {
    chrome.storage.local.get(CONFIG_KEY, function(data) {
      resolve(data[CONFIG_KEY]);
    });
  });
}

function getStoredImage() {
  return new Promise(resolve => {
    chrome.storage.local.get(IMAGE_KEY, function(data) {
      resolve(data[IMAGE_KEY] || []);
    });
  });
}

function formatFileName(template, data) {
  return template
    .replace(/\{NO\}/g, data.NO)
    .replace(/\{PAGE_TITLE\}/g, data.PAGE_TITLE)
    .replace(/\{NAME\}/g, data.NAME)
    .replace(/\{DATE\}/g, data.DATE)
    .replace(/\{EXT\}/g, data.EXT);
}

function processTitle(data) {
  return data
    .replace('-今日头条', '')
    .replace('fafa920209：', '')
    .replace('...', '')
    .replace('......', '')
    .replace(/：/g, '-')
    .replace(/\s/g, '');
}

// 打包下载：images[{ src, fileName }]
async function packageDownload(images) {
  const { title: PAGE_TITLE } = await getStored(PAGE_KEY);
  const zip = new JSZip();
  for (const item of images) {
    const { src, fileName } = item;
    try {
      const response = await fetch(src);
      const buffer = await response.arrayBuffer();
      zip.file(fileName, buffer, { binary: true });
    } catch (e) {
      console.error(`Error downloading ${src}:`, e);
    }
  }
  // 生成ZIP文件的Blob对象
  const content = await zip.generateAsync({ type: 'blob' });
  chrome.downloads.download({
    url: URL.createObjectURL(content),
    saveAs: false,
    filename: `${processTitle(PAGE_TITLE)}.zip`,
    conflictAction: 'uniquify',
  });
}

async function downloadFile(src, filename) {
  chrome.downloads.download({
    url: src,
    saveAs: false,
    filename,
    conflictAction: 'uniquify',
  });
}

function tabsQuery() {
  return new Promise(resolve => {
    chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {
      resolve(tabs);
    });
  });
}

function tabsSendMessage(tabs, params) {
  return new Promise(resolve => {
    chrome.tabs.sendMessage(tabs[0].id, params);
    resolve();
  });
}

function tabsCreate(url) {
  return new Promise(resolve => {
    chrome.tabs.create({ url, active: true });
    resolve();
  });
}

function runtimeOnMessage() {
  return new Promise(resolve => {
    chrome.runtime.onMessage.addListener(function(response, sender, sendResponse) {
      resolve({ response, sender, sendResponse });
    });
  });
}

// 匹配第一个?符号之前的内容
function getContentRegexp(str) {
  const regexBeforeQuestionMark = /^(.*?)(\?|$)/;
  const match = str.match(regexBeforeQuestionMark);
  return match ? match[1] : '';
}

function getFileInfo(url, params = {}) {
  const [str] = url.match(/[^/]+$/);
  let [fileName, ext] = getContentRegexp(str).split('.');
  if (ext == 'image') {
    ext = 'webp';
  }
  return { NAME: fileName, EXT: ext, ...params };
}

const SORTING_FUNCTIONS = {
  '原网排序': (a, b) => a.index - b.index,
  '大图优先': (a, b) => b.area - a.area,
  '小图优先': (a, b) => a.area - b.area,
};

async function getImageArr(imageList) {
  const { imageSorting, fileName } = await getStoredConfig();
  const imageArr = imageList || await getStoredImage();
  const sortedImageArr = imageArr.sort(
    SORTING_FUNCTIONS[imageSorting] || ((a, b) => a.index - b.index),
  );
  return sortedImageArr.map((img, index) => {
    const fileInfo = getFileInfo(img.src, {
      PAGE_TITLE: processTitle(img.pageTitle),
      NO: index + 1,
      DATE: new Date().getTime(),
    });
    img.fileName = formatFileName(fileName, fileInfo);
    return img;
  });
}

async function writeToFile(fileHandle, data) {
  const writableStream = await fileHandle.createWritable();
  await writableStream.write(data);
  await writableStream.close();
}

async function saveDataToFile() {
  try {
    const [fileHandle] = await window.showSaveFilePicker({
      types: [
        {
          description: 'JSON File',
          accept: {
            'application/json': ['.json'],
          },
        },
      ],
    });
    const dataToWrite = JSON.stringify(someData);
    await writeToFile(fileHandle, dataToWrite);
  } catch (e) {
    console.log(e);
  }
}

async function readFile(fileHandle) {
  const file = await fileHandle.getFile();
  return await file.text();
}

async function openAndReadFile() {
  try {
    const [fileHandle] = await window.showOpenFilePicker({
      types: [
        {
          description: 'JSON Files',
          accept: {
            'application/json': ['.json'],
          },
        },
      ],
    });
    const fileContent = await readFile(fileHandle);
    return JSON.parse(fileContent);
  } catch (e) {
    console.log(e);
  }
}
